<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Controller\AbstractController;
use App\Model\Admin\Admin;
use App\Model\ChargeDetail;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\DeviceSignalLog;
use App\Model\DistributorDevice;
use App\Model\Distributors;
use App\Model\Normal;
use App\Model\Order;
use App\Services\FileService;
use App\Services\Iot\IotService1 as IotService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Redis\Redis;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Trait\ResponseMsg;

class DevicesController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Device $device;
    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected Admin $admin;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }



    public function jtList(RequestInterface $request): ResponseInterface
    {

        $page = $request->inputs(['page', 'limit', 'is_new', 'min_sn', 'max_sn', 'time', 'inline', 'is_refund', 'station_id', 'distributor_id', 'is_active', 'sn', 'is_disabled', 'iot_sn']);
        $query = Device::where(function ($query) use ($page) {
            $query->where('distributor_id',15210);
            if ($page['iot_sn']) {
                $query->where('iot_sn', $page['iot_sn']);
            }
            if ($page['sn']) {
                $query->where('sn', $page['sn']);
            } else {
                if ($page['min_sn']) {
                    $query->where('sn', '>=', $page['min_sn']);
                }
                if ($page['max_sn']) {
                    $query->where('sn', '=<', $page['max_sn']);
                }
            }
            if ($page['is_new'] != '') {
                $query->where('is_new', $page['is_new']);
            }
            if ($page['station_id']) {
                $query->where('station_id', $page['station_id']);
            }
            if ($page['inline'] != '') {
                $query->where('inline', $page['inline']);
            }
            if ($page['is_refund'] != '') {
                $query->where('is_refund', $page['is_refund']);
            }
            if ($page['is_active'] != '') {
                $query->where('is_active', $page['is_active']);
            }
            if (isset($page['time']) && is_array($page['time'])) {
                $query->where('created_at', '>=', $page['time'][0]);
                $query->where('created_at', '<=', $page['time'][1]);
            }
        })
            ->withCount('orders')
            ->with('charge')
            ->with('station');
        $data['total'] = $query->count();
        $data['list'] = $query
            ->orderBy('id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])->get();
        foreach ($data['list'] as $k => $v) {
            $data['list'][$k]['profit'] = DistributorDevice::where('device_id', $v['id'])->sum('profit');
        }
        return $this->success($data);
    }


    /**设备列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request): ResponseInterface
    {
        $page = $request->inputs(['page', 'limit', 'is_new', 'min_sn', 'max_sn', 'time', 'inline', 'is_refund', 'station_id', 'distributor_id', 'is_active', 'sn', 'is_disabled', 'iot_sn']);
        $page['info'] = $this->distributors->getInfo($request);
        $data['list'] = Device::where(function ($query) use ($page) {
                if ($page['iot_sn']) {
                    $query->where('iot_sn', $page['iot_sn']);
                }
                if ($page['sn']) {
                    $query->where('sn', $page['sn']);
                } else {
                    if ($page['min_sn']) {
                        $query->where('sn', '>=', $page['min_sn']);
                    }
                    if ($page['max_sn']) {
                        $query->where('sn', '=<', $page['max_sn']);
                    }
                }
                if ($page['is_disabled'] != '') {
                    $query->where('is_disabled', $page['is_disabled']);
                }
                if ($page['is_new'] != '') {
                    $query->where('is_new', $page['is_new']);
                }
                if (isset($page['distributor_id']) && $page['distributor_id']) {
                    $query->where('child_distributor_id', $page['distributor_id']);
                } else {
                    if($page['info']['level'] == 2){
                        $query->where('child_distributor_id', $page['info']['id']);
                    }else{
                        $query->where('distributor_id', $page['info']['id']);
                    }
                }
                if ($page['station_id']) {
                    $query->where('station_id', $page['station_id']);
                }
                if ($page['inline'] != '') {
                    $query->where('inline', $page['inline']);
                }
                if ($page['is_refund'] != '') {
                    $query->where('is_refund', $page['is_refund']);
                }
                if ($page['is_active'] != '') {
                    $query->where('is_active', $page['is_active']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('created_at', '>=', $page['time'][0]);
                    $query->where('created_at', '<=', $page['time'][1]);
                }
            })
            ->withCount('orders')
            ->with('charge')
            ->with('station')
            ->orderBy('id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get()->toArray();

        foreach ($data['list'] as $k => $v) {
            if ($data['list'][$k]['child_distributor_id']) {
                $data['list'][$k]['distributor_name'] = Distributors::where('id', $data['list'][$k]['child_distributor_id'])->value('name');
            } else {
                $data['list'][$k]['distributor_name'] = Distributors::where('id', $data['list'][$k]['distributor_id'])->value('name');
            }
            $data['list'][$k]['profit'] = DistributorDevice::where('device_id', $v['id'])->sum('profit');
        }
        $data['total'] = Device::where(function ($query) use ($page) {
            if ($page['iot_sn']) {
                $query->where('iot_sn', $page['iot_sn']);
            }
            if ($page['sn']) {
                $query->where('sn', $page['sn']);
            } else {
                if ($page['min_sn']) {
                    $query->where('sn', '>=', $page['min_sn']);
                }
                if ($page['max_sn']) {
                    $query->where('sn', '=<', $page['max_sn']);
                }
            }
            if ($page['is_disabled'] != '') {
                $query->where('is_disabled', $page['is_disabled']);
            }
            if ($page['is_new'] != '') {
                $query->where('is_new', $page['is_new']);
            }
            if (isset($page['distributor_id']) && $page['distributor_id']) {
                $query->where('child_distributor_id', $page['distributor_id']);
            } else {
                if($page['info']['level'] == 2){
                    $query->where('child_distributor_id', $page['info']['id']);
                }else{
                    $query->where('distributor_id', $page['info']['id']);
                }
            }
            if ($page['station_id']) {
                $query->where('station_id', $page['station_id']);
            }
            if ($page['inline'] != '') {
                $query->where('inline', $page['inline']);
            }
            if ($page['is_refund'] != '') {
                $query->where('is_refund', $page['is_refund']);
            }
            if ($page['is_active'] != '') {
                $query->where('is_active', $page['is_active']);
            }
            if (isset($page['time']) && is_array($page['time'])) {
                $query->where('created_at', '>=', $page['time'][0]);
                $query->where('created_at', '<=', $page['time'][1]);
            }
        })->count();
        return $this->success($data);
    }

    /**批量修改俯冲参数
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function batchPower(RequestInterface $request): ResponseInterface
    {
        $full_power_min = $request->input('full_power_min', 20);
        $full_charge_time = $request->input('full_charge_time', 30);
        try {
            $list = Device::where('inline', 1)->get();
            foreach ($list as $v) {
                $v->full_power_min = $full_power_min;
                $v->full_charge_time = $full_charge_time;
                $v->save();
                $v->updateParams();
            }
            return $this->success();
        } catch (\Exception $e) {
            return $this->error(1001, $e->getMessage());
        }
    }

    /**
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function batchCreate(RequestInterface $request): ResponseInterface
    {
        $file = $request->file('file');
        $distributor = $request->input('distributor_id');
        $is_new = $request->input('is_new', 0);
        if ($distributor == 'undefined') {
            $distributor = '';
        }
        $info = $this->distributors->getInfo($request);
        $spreadsheet = IOFactory::load($file->getRealPath());
        // 选择第一个工作表
        $worksheet = $spreadsheet->getActiveSheet();
        // 获取最后一行和列
        $highestRow = $worksheet->getHighestRow();
        $highestColumn = $worksheet->getHighestColumn();
        $snExists = [];
        $iotSnExists = [];
        for ($row = 2; $row <= $highestRow; ++$row) {
            $rowData = [];
            for ($col = 'A'; $col <= $highestColumn; ++$col) {
                $rowData[] = $worksheet->getCell($col . $row)->getValue();
            }
            // 创建用户并插入数据库
            if ($rowData[0] && $rowData[1]) {
                if (strpos((string)$rowData[1], '；') !== false) {
                    $rowData[1] = explode('；', (string)$rowData[1]);
                } else {
                    $rowData[1] = explode(';', (string)$rowData[1]);
                }
                if (in_array($rowData[0], $snExists)) {
                    return $this->error(code: 1003, msg: '设备编号' . $rowData[0] . '在上传文件中重复');
                }

                if (in_array($rowData[1], $iotSnExists)) {
                    return $this->error(code: 1003, msg: '物联网编号' . $rowData[1] . '在上传文件中重复');
                }

                $snExists[] = $rowData[0];
                $iotSnExists[] = $rowData[1];
            }
        }

        Db::beginTransaction();
        // 读取数据并插入数据库
        try {
            for ($row = 2; $row <= $highestRow; ++$row) {
                $rowData = [];
                for ($col = 'A'; $col <= $highestColumn; ++$col) {
                    $rowData[] = $worksheet->getCell($col . $row)->getValue();
                }
                // 创建用户并插入数据库
                if ($rowData[0] && $rowData[1]) {
                    $device = new Device();
                    $device->distributor_id = $info['id'];
                    if ($distributor) {
                        $device->child_distributor_id = $distributor;
                    }
                    if ($is_new != 1) {
                        $is_new = 0;
                    }
                    $device->is_new = $is_new;
                    $device->sn = $rowData[0];
                    if (strpos((string)$rowData[1], '；') !== false) {
                        $rowData[1] = explode('；', (string)$rowData[1]);
                    } else {
                        $rowData[1] = explode(';', (string)$rowData[1]);
                    }
                    $device->iot_sn = $rowData[1][0];
                    $check = Device::where('sn', $rowData[0])
                        ->first();
                    if ($check) {
                        return $this->error(code: 1002, msg: '设备编号' . $rowData[0] . '已存在 请删除该数据重新上传');
                    }

                    $check = Device::where('iot_sn', $rowData[1][0])
                        ->first();
                    if ($check) {
                        return $this->error(code: 1002, msg: '物联网编号' . $rowData[1][0] . '已存在 请删除该数据重新上传');
                    }
                    $device->save();
                }
            }
            Db::commit();
            return $this->success(msg: '导入成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->error(code: 1002, msg: '导入失败，请检查文件内容是否符合规范' . $e->getMessage());
        }
    }

    /**生成二维码
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function qrCode(RequestInterface $request): ResponseInterface
    {
        $deviceId = $request->input('deviceId');
        $img = FileService::creatCode($deviceId);
        return $this->success($img);
    }

    /**修改状态
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function changeStatus(RequestInterface $request): ResponseInterface
    {
        $status = $request->input('status', 0, 'int');
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(code: 1001, msg: '缺失参数id');
        }
        $this->device->where('id', $id)->update(['is_active' => $status]);
        return $this->success(msg: '修改成功');
    }

    /**创建
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $info =  $this->distributors->getInfo($request);
        $data = $request->post();
        if (array_key_exists('station_name', $data)) {
            unset($data['station_name']);
        }
        if (array_key_exists('charge', $data)) {
            unset($data['charge']);
        }
        if (array_key_exists('station', $data)) {
            unset($data['station']);
        }
        if (array_key_exists('distributor_name', $data)) {
            unset($data['distributor_name']);
        }
        if (array_key_exists('port_status', $data)) {
            unset($data['port_status']);
        }
        if (array_key_exists('profit', $data)) {
            unset($data['profit']);
        }
        if (array_key_exists('order_count', $data)) {
            unset($data['order_count']);
        }
        if(array_key_exists('device_count',$data)){
            unset($data['device_count']);
        }
        if (array_key_exists('charge_name', $data)) {
            unset($data['charge_name']);
        }
        if (!$data['station_id']) {
            $data['station_id'] = 0;
        }

        if (!$data['distributors']) {
            if($info['level'] == 1){
                $data['distributor_id'] = $info['id'];
                $data['child_distributor_id'] = 0;
            }else{
                $data['distributor_id'] = $info['parent_id'];
                $data['child_distributor_id'] = $info['id'];
            }
        } else {
            if($info['level'] == 1){
                $data['child_distributor_id'] = $data['distributor_id'] ;
                $data['distributor_id'] = $info['id'];
            }else{
                $data['distributor_id'] = $info['parent_id'];
                $data['child_distributor_id'] = $data['distributor_id'] ;
            }

        }
        unset($data['distributors']);
        if (array_key_exists('id', $data) && $data['id'] > 0) {
            $id = $data['id'];
            unset($data['id']);
            $check = Device::where('sn', $data['sn'])
                ->where('id', '<>', $id)
                ->count();
            if ($check) {
                return $this->error(1002, '已存在该设备编号');
            }
            $check = Device::where('iot_sn', $data['iot_sn'])
                ->where('id', '<>', $id)
                ->count();
            if ($check) {
                return $this->error(1002, '已存在该物联网编号');
            }
            if (array_key_exists('updated_at', $data)) {
                unset($data['updated_at']);
            }
//            if ($data['is_disabled'] == 1 && $data['child_distributor_id'] == 0) {
//                return $this->error(1002, '一级经销商直属设备不可设置不统计');
//            }
            $this->device->where('id', $id)->update($data);
        } else {
            $check = Device::where('sn', $data['sn'])
                ->count();
            if ($check) {
                return $this->error(1002, '已存在该设备编号');
            }
            $check = Device::where('iot_sn', $data['iot_sn'])
                ->count();
            if ($check) {
                return $this->error(1002, '已存在该物联网编号');
            }
//            if ($data['is_disabled'] == 1 && $data['child_distributor_id'] == 0) {
//                return $this->error(1002, '一级经销商直属设备不可设置不统计');
//            }
            Device::create($data);
        }
        return $this->success();
    }

    /**批量修改
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function batchChange(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $page = $request->inputs(['ids', 'disIds','charge_id']);
        if ($page['ids']) {
            $page['ids'] = json_decode($page['ids'], true);
        } else {
            return $this->error(1001, '请先选择数据');
        }
        if (!$page['disIds']) {
            return $this->error(1001, '请先选择经销商');
        }
        $data['distributor_id'] = $page['disIds'][0];
        if (array_key_exists('1', $page['disIds'])) {
            $data['child_distributor_id'] = $page['disIds'][1];
        } else {
            $data['child_distributor_id'] = 0;
        }
        if(isset($page['charge_id'])){
            $data['charge_id'] = $page['charge_id'];
        }
        Device::whereIn('id', $page['ids'])
            ->update($data);
        return $this->success();
    }

    /**删除
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        $check = Order::where('device_id', $id)->count();
        if ($check > 0) {
            return $this->error(1001, '设备已创收并有相关订单 为保证数据完整性请勿删除');
        }
        $this->device->where('id', $id)->delete();
        return $this->success();
    }

    /**恢复出场设置
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function unbind(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        $device = Device::find($id);
        $device->station_id = 0;
        $device->charge_id = 0;
        $device->child_distributor_id = 0;
        $device->save();
        Order::where('device_id', $id)->update(['is_draw' => 1]);
        DistributorDevice::where('device_id', $id)->update(['profit' => 0]);
        return $this->success();
    }


    /**复位设备
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function reset(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        $device = $this->device->where('id', $id)->first();
        $device->distributor_id = 0;
        $device->child_distributor_id = 0;
        $device->station_id = 0;
        $device->charge_id = 0;
        $device->deposit = 0;
        $device->active_at = null;
        $device->expires_at = null;
        try {
            $device->save();
            return $this->success(msg: '复位成功');
        } catch (\Exception $e) {
            return $this->error(msg: $e->getMessage());
        }
    }

    /**读取设备参数
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function readParams(RequestInterface $request): ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        try {
            $device = $this->device->where('id', $id)->first();
            if (!$device) {
                return $this->error(1001, '设备不存在');
            }
            IotService::readParams($device->iot_sn);
            return $this->success(msg: '读取成功 请稍后刷新列表查看');
        } catch (\Exception $e) {
            return $this->error(msg: $e->getMessage());
        }
    }

    /**更新设备参数
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function updateParams(RequestInterface $request): ResponseInterface
    {
        $params = $request->post();
        $device = $this->device->where('sn', $params['sn'])
            ->first();
        try {
            if ($device) {
                $device->update($params);
                $device->updateParams();
                return $this->success(msg: '更新成功 请稍后查看');
            }
            return $this->error('1002', '设备不存在');
        } catch (\Exception $e) {
            return $this->error('1001', '操作繁忙 请稍后重试');
        }
    }


    /**开启端口设备
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function startPort(RequestInterface $request): ResponseInterface
    {
        $params = $request->post();
        $imei = $this->device->where('sn', $params['sn'])->first();
        if ($imei && $imei->iot_sn) {
            if ($imei->is_new) {
                $charge = ChargeOption::where('distributor_id', 0)
                    ->where('is_del', 1)
                    ->first();
                IotService::startNew($imei->iot_sn, $params['port'], $charge, $params['fee'], $params['minutes'], 100);
            } else {
                IotService::start($imei->iot_sn, $params['port'], $params['minutes'], $params['fee']);
            }
            return $this->success();
        }
        return $this->error(1001, '设备物联网编号不存在');
    }

    /**根据经销商获取设备
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function distributorDevices(RequestInterface $request): ResponseInterface
    {
        $distributorId = $request->input('distributor_id');
        $distributorModel = Distributors::where('id', $distributorId)->first();
        if ($distributorModel->level == Distributors::LEVEL_1) {
            $data = $this->device->where('distributor_id', $distributorId)
                ->where('child_distributor_id', 0)
                ->where('is_active', 1)
                ->get(['id', 'sn', 'iot_sn']);
        } else {
            $data = $this->device->where('child_distributor_id', $distributorId)
                ->where('is_active', 1)
                ->get(['id', 'sn', 'iot_sn']);
        }
        return $this->success($data);
    }

    /**获取最近回传的20条
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getSignalList(RequestInterface $request): ResponseInterface
    {
        $devId = $request->input('device_id');
        $list = DeviceSignalLog::where('device_id', $devId)
            ->orderBy('id', 'desc')
            ->limit(20)
            ->get();
        return $this->success($list);
    }


    public function getCharge(RequestInterface $request): ResponseInterface
    {
        $chargeId = $request->input('id', 0, 'int');
        if ($chargeId <= 0) {
            $charge = ChargeOption::where('distributor_id', 0)
                ->where('is_del', 1)->first(['id', 'name', 'distributor_id', 'is_autoload', 'fee', 'created_at', 'type', 'service_fee', 'service_type', 'elec', 'elec_price', 'pre_fee']);
        } else {
            $charge = ChargeOption::where('id', $chargeId)->first(['id', 'name', 'distributor_id', 'is_autoload', 'fee', 'created_at', 'type', 'service_fee', 'service_type', 'elec', 'elec_price', 'pre_fee']);
        }
        if (!$charge) {
            return $this->error(1001, '设备暂无可用套餐');
        }
        $charge['service_children'] = ChargeDetail::where('charge_option_id', $charge['id'])
            ->where('type', ChargeDetail::SERVICE_TYPE)
            ->orderBy('sort', 'desc')->get()->toArray();
        $charge['elec_children'] = ChargeDetail::where('charge_option_id', $charge['id'])
            ->where('type', ChargeDetail::ELEC_TYPE)
//            ->where('is_del',1)
            ->orderBy('sort', 'desc')->get(['id', 'fee', 'minutes', 'min_power', 'max_power', 'type', 'created_at', 'elec'])->toArray();
//        $charge['sp_full_empty'] = $this->device->where('sn',$sn)->value('sp_full_empty');
        $charge['power_children'] = ChargeDetail::where('charge_option_id', $charge['id'])
            ->where('type', ChargeDetail::POWER_TYPE)
//            ->where('is_del',1)
            ->orderBy('sort', 'desc')->get(['id', 'fee', 'minutes', 'min_power', 'max_power', 'type', 'created_at', 'elec'])->toArray();
        $charge['time_children'] = ChargeDetail::where('charge_option_id', $charge['id'])
            ->where('type', ChargeDetail::TIME_TYPE)
//            ->where('is_del',1)
            ->orderBy('sort', 'desc')->get(['id', 'fee', 'minutes', 'min_power', 'max_power', 'type', 'created_at', 'elec'])->toArray();
        return $this->success($charge);
    }


    public function staticsOrder(RequestInterface $request){
        $info = $this->distributors->getInfo($request);
        $devices = $request->input('devices');
        if($devices && !is_array($devices)){
            $devices = json_decode($devices,true);
        }
        $time = $request->input('time');
        if(!$time){
            $time[0] = date('Y-m-d');
            $time[1] = date('Y-m-d');
        }
        $startDate = new \DateTime($time[0]);
        $endDate = new \DateTime($time[1]);
        $interval = $startDate->diff($endDate);
// 计算绝对天数差（无论日期顺序）
        if ($interval->days > 90) {
            return $this->error(1001,'起止日期不可超过3个月');
        }
        $orderQuery = Order::query()->where('is_draw',0);
        $orderQuery->whereIn('device_id',$devices);
        $data['using_order']=(clone $orderQuery)->where('status',Order::STATUS_USING)
            ->whereBetween('created_at',[$time[0].' 00:00:00',$time[1].' 23:59:59'])->count();
        $result = (clone $orderQuery)
            ->whereIn('status', [Order::STATUS_REFUNDED, Order::STATUS_END])
            ->whereBetween('stop_at', [$time[0].' 00:00:00', $time[1].' 23:59:59'])
            ->selectRaw('
        COUNT(*) as order_count,
        COALESCE(SUM(duration_seconds), 0) as total_duration,
        COALESCE(SUM(return_fee), 0) as total_return_fee,
        COALESCE(SUM(power_fee), 0) as total_power_fee
    ')->first();
        $data['end_order'] = $result->order_count;
        $data['end_time'] = $result->total_duration;
        $data['return_fee'] = $result->total_return_fee;
        $data['power_fee'] = $result->total_power_fee;
        if($data['end_time']>0){
            $data['end_time'] = round($data['end_time']/3600,2);
        }
        $data['use_elec'] = (clone $orderQuery)->whereIn('status',[Order::STATUS_REFUNDED,Order::STATUS_END])
            ->whereBetween('created_at',[$time[0].' 00:00:00',$time[1].' 23:59:59'])
            ->where('is_fail',1)->sum('surplus_electricity');
        if($data['use_elec'] >0){
            $data['use_elec'] = round($data['use_elec']/100,2);
        }
        return $this->success($data);

    }


}
